import { setDiscount } from "@/utils/index.js"
import { reactive, toRefs, computed } from "vue"
import { onShow, onUnload, onReady, onLoad } from "@dcloudio/uni-app";
import { LoginStore } from "@/store/modules/login.js";
import { ConfigStore } from "@/store/modules/config.js";
const userInfo = computed(() => (LoginStore().userInfo))
const config = computed(() => (ConfigStore().config))
const assetApi = uniCloud.importObject('qc-asset', {
	customUI: true // 取消自动展示的交互提示界面
})
const articleApi = uniCloud.importObject('qc-article', {
	customUI: true // 取消自动展示的交互提示界面
})
const marketingApi = uniCloud.importObject('qc-marketing', {
	customUI: true // 取消自动展示的交互提示界面
})
const payApi = uniCloud.importObject('qc-pay',{
	customUI: true
})
/**
 * @description  接受邀请
 * @param rules 表单校验规则
 * */
export const usedata = (props, payRef) => {
	const state = reactive({
		priceList: {}, //广告价格
		id: '', //数据id
		price: 0, //支付金额
		showDialog: false, //公共弹窗状态
		title: '', //弹窗标题
		pinnedday: '', //广告操作（置顶，刷新。。。）天数 
		placeholder: '', //输入框提示内容
		refreshDate: '', //刷新时间
		refreshNum: '', //刷新次数
		// 头条
		headline: {
			headline_time: null, //头条天数
			is_headline: false, //是否已是头条
			showTop: false, //选择头条排名抽屉显示状态
			topList: [], //选择的数据
			headline_price: null, //头条价格
			headline_mix_time: 1, //最小头条天数
		},
		sticky_mix_time: 1, //置顶最小天数
		realNameShow: false, //实名认证弹窗
		allhongbao: null, //派发红包金额
		hongbaoNum: null ,//派发红包份数
		hongBao_money: 0, //最小红包金额
		hongBao_num: 0, //最小红包数量
		url:""
	})
	onLoad(async (e) => {
		state.hongBao_money = config.value.hongBao_money
		state.hongBao_num = config.value.hongBao_num
		// 请求广告价格
		const res = await assetApi.getPricing({ category_id: props.category_id })
		state.sticky_mix_time = res.data?.sticky_mix_time //置顶时间
		state.priceList = res.data
		state.headline.topList = res.data?.headline_cost
		state.headline.headline_price = res?.data?.headline_cost ? res?.data?.headline_cost : 0
		state.headline.headline_mix_time = res.data?.headline_mix_time
	})
	const paiMoney = (id) => {
		state.id = id
		state.showDialog = true
		state.title = '派发红包'
	}
	//我要上头条
	const onshowTop = async (id, is_headline) => {
		state.headline.headline_time = ''
		state.headline.is_headline = is_headline
		state.id = id
		// 打开弹窗
		state.showDialog = true
		state.title = '我要上头条'
	}
	// 编辑事件
	const edit = (_id) => {
		// #ifdef APP-PLUS
		const obj = [{
			url: `/pages/push/publishEdit/publishEdit?item=${JSON.stringify({_id,type:'文章',publish_type:props.type})}`
		}, {
			url: `/pages/push/publishEdit/publishEdit?item=${JSON.stringify({_id,type:'应用',publish_type:props.type})}`
		}, {
			url: `/pages/push/publishEdit/publishEdit?item=${JSON.stringify({_id,type:'人脉',publish_type:props.type})}`
		}, {
			url: ""
		}, {
			url: `/pages/push/preheat/addpreheat?item=${JSON.stringify({_id,type:'项目预热',publish_type:props.type})}`
		}, {
			url: `/pages/push/group/addgroup?item=${JSON.stringify({_id,type:'一手单',publish_type:props.type})}`
		}, {
			url: `/pages/push/firstOrder/addfirstOrder?item=${JSON.stringify({_id,type:'渠道团队',publish_type:props.type})}`
		}, {
			url: `/pages/push/publishCheater/publishCheater?item=${JSON.stringify({_id,type:'骗子曝光',publish_type:props.type})}`
		}, ]
		// #endif
		// #ifdef H5
		const obj = [{
			url: `/pages/push/publishEdit/publishEdit?item=${encodeURI(JSON.stringify({_id,type:'文章',publish_type:props.type}))}`
		}, {
			url: `/pages/push/publishEdit/publishEdit?item=${encodeURI(JSON.stringify({_id,type:'应用',publish_type:props.type}))}`
		}, {
			url: `/pages/push/publishEdit/publishEdit?item=${encodeURI(JSON.stringify({_id,type:'人脉',publish_type:props.type}))}`
		}, {
			url: ""
		}, {
			url: `/pages/push/preheat/addpreheat?item=${encodeURI(JSON.stringify({_id,type:'项目预热',publish_type:props.type}))}`
		}, {
			url: `/pages/push/group/addgroup?item=${encodeURI(JSON.stringify({_id,type:'一手单',publish_type:props.type}))}`
		}, {
			url: `/pages/push/firstOrder/addfirstOrder?item=${encodeURI(JSON.stringify({_id,type:'渠道团队',publish_type:props.type}))}`
		}, {
			url: `/pages/push/publishCheater/publishCheater?item=${encodeURI(JSON.stringify({_id,type:'骗子曝光',publish_type:props.type}))}`
		}, ]
		// #endif
		uni.navigateTo({
			url: obj[props.type].url
		})
	}

	// 置顶-推荐-榜首-事件
	const allClck = async (id, title, placeholder) => {
		if (props.type == 1 && title == "置顶") {
			state.id = id
			state.title = title
			state.placeholder = placeholder
			state.showDialog = true
		} else if (props.type == 0 && title == "我要上头条") {
			state.id = id
			state.title = title
			state.placeholder = placeholder
			state.showDialog = true
		} else {
			state.id = id
			state.title = title
			state.placeholder = placeholder
			state.showDialog = true
		}
	}
	// 置顶-推荐-榜首-头条-确认按钮事件
	const confirm = (title) => {
		const pattern = /^[1-9]\d*$/;
		if (title == "置顶") {
			if (!pattern.test(state.pinnedday)) {
				state.pinnedday = ""
				return uni.fui.toast('请输入正整数')
			} else {
				if (title == "置顶") {
					if (state.pinnedday < state.sticky_mix_time) return uni.fui.toast(
						`置顶最小天数为${state.sticky_mix_time}天`)
				}
			}
		} else if (title == "自动刷新") {
			if (!pattern.test(state.refreshNum)) {
				state.refreshNum = ""
				return uni.fui.toast('请输入正整数')
			} else if (!pattern.test(state.refreshDate)) {
				state.refreshDate = ""
				return uni.fui.toast('请输入正整数')
			} else {
				if (state.refreshNum < 2) return uni.fui.toast(`刷新次数最小为2次`)
				if (state.refreshDate < 5) return uni.fui.toast(`最小时间间隔为5分钟`)
			}
		} else if (title == "我要上头条") {
			if (!pattern.test(state.headline.headline_time)) {
				state.headline.headline_time = ""
				return uni.fui.toast('请输入正整数')
			} else {
				if (state.headline.headline_time < state.headline.headline_mix_time)
					return uni.fui.toast(`最少头条天数为${state.headline.headline_mix_time}天`)
			}
		} else if (title == "派发红包") {
			if (!pattern.test(state.allhongbao)) {
				state.allhongbao = ""
				return uni.fui.toast('请输入正整数')
			} else if (!pattern.test(state.hongbaoNum)) {
				state.hongbaoNum = ""
				return uni.fui.toast('请输入正整数')
			} else {
				if (state.allhongbao < state.hongBao_money) return uni.fui.toast(`红包最小金额为${state.hongBao_money}元`)
				if (state.hongbaoNum < state.hongBao_num) return uni.fui.toast(`红包最小份数为${state.hongBao_num}次`)
				if (state.allhongbao / state.hongbaoNum < 0.1) return uni.fui.toast(`红包每份不得低于0.1元`)
			}
		}

		if (title == '我要上头条') {
			sure()
		} else {
			onCancel()
		}
	}

	// 头条提交逻辑
	const sure = async () => {
		if (!state.headline.is_headline) {
			if (!state.headline.headline_time) {
				uni.fui.toast('请输入头条天数')
			} else {
				state.price = state.headline.headline_price * state.headline.headline_time
				let params = {
					_id: state.id, //数据id
					publish_type: props.type,
					is_headline: true,
					headline_time: state.headline.headline_time
				}
				// 关闭下拉框
				onClose()
				// 调用支付
				createPayment(params)
			}
		} else {
			if (!state.headline.headline_time) return uni.fui.toast('请输入天数')
			state.price = state.headline.headline_price * state.headline.headline_time
			let params = {
				_id: state.id, //数据id
				publish_type: props.type,
				is_headline: true,
				headline_time: state.headline.headline_time
			}
			// 关闭下拉框
			onClose()
			// 调用支付
			createPayment(params)
		}
	}


	// 置顶-自动刷新-派发红包提交逻辑
	const onCancel = async () => {
		if (state.title == '自动刷新') {
			if (!state.refreshDate || !state.refreshNum) return uni.fui.toast('请输入间隔时间和次数')
		} else if (state.title == '置顶') {
			if (!state.pinnedday) return uni.fui.toast('请输入天数')
		}
		let params = {}
		if (state.title == '置顶') {
			state.price = state.pinnedday * state?.priceList?.sticky_cost
			params = {
				_id: state.id, //数据id
				publish_type: props.type,
				is_sticky: true,
				sticky_time: state.pinnedday
			}
		} else if (state.title == '自动刷新') {
			state.price = state?.priceList?.autoRefresh_cost * state?.refreshNum
			params = {
				_id: state.id, //数据id
				publish_type: props.type,
				is_auto_refresh: true,
				auto_refresh_num: state.refreshNum,
				auto_refresh_minute: state.refreshDate
			}
		} else {
			// 派发红包
			state.price = state?.allhongbao
			params = {
				_id: state.id, //数据id
				publish_type: props.type,
				hongBao: true,
				hongBao_money: state.allhongbao,
				hongBao_num: state.hongbaoNum
			}
		}
		onClose()
		// 调用支付
		createPayment(params)
	}


	// 关闭头条-置顶-自动刷新-弹窗
	const onClose = () => {
		state.showDialog = false
		state.pinnedday = ''
	}

	// 删除事件
	const remove = (id) => {
		state.id = id
		state.showDialog = true
		state.title = '删除'
	}
	//删除确认事件
	const onClick = async (e) => {
		//点击确定
		if (e.index == 1) {
			const res = await articleApi.deleteAd({
				publish_type: props.type,
				_id: state.id
			})
			uni.fui.toast(res.errMsg)
			uni.$emit('update', true)
			uni.$emit('resetUpScroll')
		}
		onClose()
	}

	// 内容详情事件
	const goDetail = (item) => {
		const params = { _id: item._id, publish_type: props.type }
		// #ifdef APP-PLUS
		const obj = [{
			url: `/pages/push/wzDetail/wzDetail?item=${JSON.stringify(params)}`
		}, {
			url: `/pages/tabbar/application/appDetail?item=${JSON.stringify(params)}`
		}, {
			url: ``
		}, {
			url: ""
		}, ]
		// #endif
		// #ifdef H5
		const obj = [{
			url: `/pages/push/wzDetail/wzDetail?item=${encodeURI(JSON.stringify(params))}`
		}, {
			url: `/pages/tabbar/application/appDetail?item=${encodeURI(JSON.stringify(params))}`
		}, {
			url: ``
		}, {
			url: ""
		}]
		// #endif
		uni.navigateTo({
			url: obj[props.type].url
		})
	}

	//刷新事件
	const refresh = async (id) => {
		state.title = '刷新'
		let params = {
			_id: id, //数据id
			publish_type: props.type,
			is_refresh: true
		}
		state.price = state.priceList.refresh_cost
		createPayment(params)
	}


	// 发起支付
	const createPayment = (params) => {
		// 判断是否有刷新或者自动刷新或者置顶，如果是手动刷新的话，time传入1，如果是自动刷新的话，time传入刷新的次数，如果是置顶的话time出入置顶的天数
		payRef.value.open({
			data: {
				total_price: state.price,
				custom: params?.is_refresh ? { couponType: 1, time: 1 } : params?.is_sticky ?
				{ couponType: 0, time: params?.sticky_time } : params?.is_auto_refresh ?
				{ couponType: 1, time: params?.auto_refresh_num } : null, //刷新卡+置顶卡
				total_fee: setDiscount(userInfo?.value?.vipPower?.discount, state.price),
				subject: props.name + '-' + state.title,
				body: props.name + '-' + state.title,
				type: 'goods',
			},
			onCreate: res => {

			},
			onSuccess: async (res) => {
				if (res.code == 0 && res.user_order_success) {
					if (res.orderPaid == false && res.url) {
						params['type_id'] = params['_id']
						delete params._id
						const resApi = await payApi.addOrdersLog({
							...params,
							user_id:userInfo.value._id,
							out_trade_no: res.out_trade_no,
							key:props.name + '-' + state.title
						})
						if(resApi.id){
							// #ifdef APP-PLUS
							state.url = res.url
							// #endif
							// #ifdef H5
							uni.navigateTo({
								url:`/pages/webView/webView?u=${encodeURIComponent(JSON.stringify(res.url))}`
							})
							// #endif
						}
					}else{
						const res1 = await articleApi.setRanking({
							...params,
							user_id: userInfo.value._id
						})
						uni.fui.toast(res1.errMsg)
						uni.$emit('resetUpScroll')
						uni.$emit("fn", res.out_trade_no)
					}
				}
			},
			onFail: res => {

			},
			onCancel: res => {

			}
		})
	}

	return {
		...toRefs(state),
		onshowTop,
		onClose,
		edit,
		remove,
		onClick,
		goDetail,
		refresh,
		allClck,
		confirm,
		paiMoney
	};
};